﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace GameClient
{
    class Lengthcode
    {
        /// <summary>
        /// 长度编码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] LengthECode(byte[] data)
        {
            if (data != null&&data.Length>0)
            { 
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(data.Length);//写入数据长度（包头），int类型一共4个字节
            bw.Write(data);
            byte[] result = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(),0,result,0,(int)ms.Length);//提取ms流中的数据给result
            ms.Close();
            bw.Close();
            return result;
            }
            return null;
        }
        /// <summary>
        /// 长度解码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] LengthDeCode(ref List<byte> data)
        {
            if (data==null || data.Count < 4)
            {
                return null;
            }
            MemoryStream ms = new MemoryStream(data.ToArray());
            BinaryReader br = new BinaryReader(ms);
            int length = br.ReadInt32(); //包头
            if (data.Count - 4 < length)//检测传进的缓存区长度与包头比较，如果不够4个字节，证明数据没接收完，返回让其继续接受
            {
                ms.Close();
                br.Close();
                return null;
            }
            byte[] result = new byte[length];
            Buffer.BlockCopy(data.ToArray(), 4, result, 0, length);//提取ms流中的数据给result
            ms.Close();
            br.Close();
            data.RemoveRange(0, length + 4);
            return result;
        }
    }
}
